<template>
	<view>
		<view class="loginTop posRel">
			<image class="samePar posAbso" src="../../static/images/logBg_top.png"></image>
			<image src="../../static/images/logo.png" class="logo posAbso"></image>
		</view>
		<view class="loginForm">
			<view class="loginForm">
				<view class="loginItem hasFlex posRel">
					<view class="iconView">
						<view class="iconfont icon-shoujihao"></view>
					</view>
					<input type="tel" class="input" name="phoneNum" v-model="phoneNum" placeholder="请输入账号" maxlength="20" placeholder-style="font-weight:normal;color:#aeaeae;"/>
				</view>
				<view class="loginItem hasFlex">
					<view class="iconView">
						<view class="iconfont icon-mima"></view>
					</view>
					<input type="password" class="input" name="password" v-model="password" placeholder="请输入密码"  placeholder-style="font-weight:normal;color:#aeaeae;"/>
				</view>
				<view class="smFun hasFlex">
					<view @tap="goSetPwd">忘记密码</view>
					<view @tap="goReg">立即注册</view> 
				</view>
				<button class="loginBtn" :loading="isDisabled" :disabled="isDisabled" @tap="goLogin">{{loginTxt}}</button>
				<view class="agree hasFlex" @tap="shouldAgree">
					<view class="check" :class="[isAgreeFlag ? 'active' : '']">
						<view class="iconfont icon-duihao"></view>
					</view>
					<view class="agreeTxt">登录即同意<text class="detTxt" @tap.stop="goFwxy">《用户协议》</text>、<text class="detTxt" @tap.stop="goYszc">《隐私政策》</text>和<text class="detTxt" @tap.stop="goSqgf">《社区规范》</text></view> 
				</view> 
			</view>
			<!-- 快捷登录 -->
			<!-- <view class="fastLogin">
				<view class="fastLoginTop">
					<view>———</view> 
					<view class="txt">快捷登录</view>
					<view>———</view>
				</view>
				<view class="fastLoginBot">
					<view class="iconfont icon-weixin"></view>
					<button @tap="wxAuthLogin" class="comBtn">授权登录</button>
				</view>
			</view> -->
		</view>
		<view class="loginBot">
			<image class="samePar" src="../../static/images/logBg_bot.png"></image>
		</view>
		<uni-popup type="bottom" ref="loginTips">
			<view class="popuoView">
				<view class="popTit">用户协议及隐私政策</view>
				<view class="popCon">我已阅读并同意<text class="specCol" @tap="goFwxy">用户协议</text><text class="specCol" @tap="goYszc">隐私政策</text>和<text class="specCol" @tap="goSqgf">社区规范</text>并授权和心云登录</view>
				<view class="popBtn">
					<button class="comBtn" :loading="isDisabled" :disabled="isDisabled" @tap="goLoginPop">{{authBtnTit}}</button>
					<view class="noAgreeTxt" @tap="handleClose">不同意</view>
				</view>
			</view>
		</uni-popup> 
	</view>
</template>

<script>
	import { commonLogin,wxAuthLog,checkUnionId,wxUserLogin } from '@/api/authLogin'
	export default {
		data() {
			return {
				phoneNum:'',
				password:'',
				isAgreeFlag:false,
				loadOpt : '',
				isDisabled:false,
				loginTxt:'登录',
				res:null,
				canRefreshFlag:0,//loadOpt == '' 时 0上个页面不刷新接口 1上个页面刷新接口
				loginType:'',
				authBtnTit:'同意并登录'
			}
		},
		onLoad(options){
			//userFix->关注 去预约
			this.canRefreshFlag = options.canRefreshFlag == undefined ? 0 : options.canRefreshFlag;
			this.loadOpt = options.loadOpt == undefined ? '' : options.loadOpt;
		},
		onShow(){
			if(uni.getStorageSync('logAcc') != ''){
				this.phoneNum = uni.getStorageSync('logAcc');
				this.isAgreeFlag = true;
			}
		},
		methods: {
			handleClose(){
				this.$refs.loginTips.close();
				this.loginType = '';
			},
			wxAuthLogin(){
				if(!this.isAgreeFlag){
					this.loginType = 'wxAuth';
					this.$refs.loginTips.open();
					return;
				}
				this.getUserProfile();
			},
			goLoginPop(){
				if(this.loginType == 'accLogin'){
					this.commonAccLogin();
				}else{
					this.getUserProfile()
				}
			},
			getUserProfile(){
				uni.showLoading({ title: '授权中...', mask: true });
				this.isDisabled = true;
				this.authBtnTit = '授权中...';
				this.loginTxt = '登录中...';
				uni.login({
					provider : 'weixin',
					success:(resLogin)=>{
						if(resLogin.code){ 
							uni.getUserInfo({
								success:(resUserInfo_1)=>{
									var field = {code:resLogin.code,appletName:'cp'};
									wxAuthLog(field).then(resAuth=>{
										uni.setStorageSync('userOpenId',resAuth.data.datas[0].openId);
										var tmpSessionKey = resAuth.data.datas[0].sessionKey,
											tmpUnionId = resAuth.data.datas[0].unionId,
											tmpOpenId = resAuth.data.datas[0].openId;
										var loginField = { encryptedData:resUserInfo_1.encryptedData,iv:resUserInfo_1.iv,sessionKey:tmpSessionKey,unionId:tmpUnionId,openId:tmpOpenId };
										var fieldCheck = {unionId:tmpUnionId};
										checkUnionId(fieldCheck).then(res=>{//直接登录
											uni.showLoading({ title: '登录中...', mask: true });
											this.authBtnTit = '登录中...';
											var tmpLogField = { mobile:res.data.datas,opt:'visitor',client:'applet' }
											Object.assign( loginField,tmpLogField );
											wxUserLogin(loginField).then(res=>{
												uni.hideLoading();
												//console.log(res)
												let tmpRes = res.data.datas;
												this.User.token = tmpRes.token;
												this.User.userIdPss = tmpRes.userId;
												uni.setStorageSync("token", this.User.token);
												uni.setStorageSync("userIdPss",this.User.userIdPss);
												uni.setStorageSync('logAcc',tmpRes.account);
												uni.setStorageSync('userPortrait',tmpRes.userPortrait);
												uni.setStorageSync('nickName',tmpRes.netName);
												this.util.showToastSuc('登录成功');
												uni.$emit('changeLoginStaToLogin');
												if(this.loadOpt == ''){
													setTimeout(()=>{
														uni.switchTab({
															url:'/pages/index/index'
														})
													},1500);
												}else if(this.loadOpt == 'userFixNoRef'){
													uni.navigateBack({
														delta:1
													})
												}else{
													if(this.canRefreshFlag == 1){
														let pages = getCurrentPages();
														let prevPage = pages[pages.length - 2];
														prevPage.$vm.isRefreshFlag = true;
													}
													uni.navigateBack({
														delta:1
													})
												}
											}).catch(err=>{
												this.isDisabled = false;
												this.authBtnTit = '同意并登录';
												this.loginTxt = '登录';
											})
										}).catch(err=>{
											if(err.data.code == 50001){
												uni.setStorageSync('loginField',loginField);
												uni.navigateTo({
													url:'../bindPhone/bindPhone?loadOpt=' + this.loadOpt + '&canRefreshFlag=' + this.canRefreshFlag,
													success:()=>{
														this.$refs.loginTips.close();
														this.isDisabled = false;
														this.authBtnTit = '同意并登录';
														this.loginTxt = '登录';
													}
												})
											}
										})
									}).catch(err=>{
										console.log(err)
									})
								},fail:(err)=>{
									// console.log(err)
									uni.hideLoading();
									this.isDisabled = false;
									this.authBtnTit = '同意并登录';
									this.$refs.loginTips.close();
									this.util.showToast('为了您更好的体验,请先同意授权');
								}
								
							})
						}
					}
				})
			},
			shouldAgree(){
				this.isAgreeFlag = !this.isAgreeFlag;
			},
			commonAccLogin(){
				var field = {account:this.phoneNum,password:this.password};
				this.isDisabled = true;
				this.loginTxt = '登录中...';
				uni.showLoading({ title: '登录中...', mask: true });
				commonLogin(field).then(res=>{
					let tmpRes = res.data.datas;
					this.token = tmpRes.token;
					this.User.userIdPss = tmpRes.userId;
					uni.setStorageSync("token", this.token);
					uni.setStorageSync("userIdPss",this.User.userIdPss);
					uni.setStorageSync('logAcc',tmpRes.account);
					uni.setStorageSync('userPortrait',tmpRes.userPortrait);
					uni.setStorageSync('nickName',tmpRes.netName);
					uni.$emit('changeLoginStaToLogin');
					
					// 返回上一步
					if(this.loadOpt == ''){
						uni.switchTab({
							url:'/pages/index/index' 
						})
					}else{
						if(Number( this.canRefreshFlag ) == 1){
							let pages = getCurrentPages();
							let prevPage = pages[pages.length - 2];
							prevPage.$vm.isRefreshFlag = true;
						}
						uni.navigateBack({ delta: 1 });
					}
					setTimeout(()=>{
						this.util.showToastSuc('登录成功');
					},500);
				}).catch(err=>{
					this.isDisabled = false;
					this.loginTxt = '登录';
					if(err.data.code == 20002){
						uni.showToast({'title':'账号不存在或密码错误','icon':'none'});
					}else if(err.data.code == 20004){
						uni.showToast({'title':'账号不存在','icon':'none'});
					}
				})
			},
			goLogin(){
				if(this.phoneNum == ''){
					this.util.showToast('请输入账号');
				}else if(this.password == ''){
					this.util.showToast('请输入密码');
				}else if(!this.isAgreeFlag){
					this.loginType = 'accLogin';
					this.$refs.loginTips.open();
				}else{
					this.commonAccLogin();
				}
			},
			//忘记密码
			goSetPwd(){
				uni.navigateTo({
					url:'../subMine/setPwd/setPwd?opt=setPwd&loginStatus=0'
				})
			},
			goReg(){
				uni.navigateTo({
					url:'/pages/subMine/setPwd/setPwd?opt=regAcc'
				})
			},
			goFwxy(){
				uni.navigateTo({
					url:'../protocol/protocol?xyId=1'
				})
			},
			goYszc(){
				uni.navigateTo({
					url:'../protocol/protocol?xyId=2'
				})
			},
			//社区规范
			goSqgf(){
				uni.navigateTo({
					url:'../protocol/protocol?xyId=4'
				})
			}
		}
	}
</script>
<style lang="scss">
	page{background:#fff;}
</style>
<style lang="scss" scoped>
	@import '@/static/scss/login.scss';
	.fastLogin{
		width: 100%;
		position: relative;
		z-index: 11;
		margin-top: 120rpx;
		.fastLoginTop{
			width: 100%;
			height: 30rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: $font-size24;
			color: $pss-text-colora;
			.txt{
				margin:0 10rpx;
			}
		}
		.fastLoginBot{
			display: flex;
			justify-content: center;
			margin-top: 30rpx;
			position: relative;
			.comBtn{
				width: 80%;
				position: absolute;
				left: 10%;
				top: -15rpx;
				opacity: 0;
			}
			.icon-weixin{
				font-size: 70rpx;
				color: #00c495;
			}
		}
	}
</style>
